<template>
  <div>
    <m-shelf title="我的订单">
      <div slot="right">
        <el-select size="mini" v-model="queryInfo.status" placeholder="请选择" clearable @change="handleChange">
          <el-option
              v-for="item in cateList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
        </el-select>
      </div>
      <div slot="content">
        <div v-loading="loading" element-loading-text="加载中..." v-if="orderlist.length" style="min-height: 10vw;">
          <div v-for="(item,i) in orderlist" :key="i">
            <div class="gray-sub-title cart-title">
              <div class="first">
                <div>
                  <span class="date" v-text=" dateFormat(item.createdAt)"></span>
                  <span class="order-id"> 订单号： <a @click="goOrderDetail(item.order_number)">{{item.order_number}}</a> </span>
                </div>
                <div class="f-bc">
                  <span class="price">单价</span>
                  <span class="num">数量</span>
                  <span class="operation">商品操作</span>
                </div>
              </div>
              <div class="last">
                <span class="sub-total">实付金额</span>
                <span class="order-detail"> <a @click="delOrder(item.id, item.order_number)">删除订单 ><em class="icon-font"></em></a> </span>
              </div>
            </div>
            <div class="pr">
              <div class="cart" v-for="(good,j) in item.goods_info" :key="j">
                <div class="cart-l" :class="{bt:j>0}">
                  <a @click="goodsDetails(good.goods_id)">
                    <div class="car-l-l" >
                      <div class="img-box" >
                        <img :src="'http://127.0.0.1:8000/' + good.mp_good.goods_Bigimg" alt="">
                      </div>
                      <div class="ellipsis">
                        <a style="color: #626262;">{{good.mp_good.goods_name}}</a>
                      </div>
                    </div>
                  </a>
                  <div class="cart-l-r">
                    <div>¥ {{Number(good.goods_price).toFixed(2)}}</div>
                    <div>{{good.goods_number}}</div>
                    <div>
                      <el-tooltip effect="dark" content="查看物流信息" placement="top">
                        <el-button style="margin-left:35px" type="success" icon="el-icon-location" circle @click="showProgressBox(item)" v-if="item.status === 2" class="del-order"></el-button>
                      </el-tooltip>

                      <el-tooltip effect="dark" content="写下您的评价吧" placement="top">
                        <el-button style="margin-left:35px" type="primary" icon="el-icon-edit" circle @click="openCommentVisible(item.goods_info[j])" v-if="item.status === 3 && !item.goods_info[j].is_comment" class="del-order"></el-button>
                      </el-tooltip>
                    </div>
                  </div>
                </div>
                <div class="cart-r">
                  <span></span>
                  <span></span>
                </div>
              </div>
              <div class="prod-operation pa" style="right: 0;top: 0;">
                <div class="total">¥ {{ item.total }}</div>
                <div v-if="item.status === 0">
                  <el-button style="margin-left:-10px" @click="orderPayment(item.order_number, item.total)" type="primary" size="small">现在付款</el-button>
                </div>
                <div v-if="item.status === 1">
                  <div style="margin-left: 5px">
                    已付款
                  </div>
                </div>
                <div v-if="item.status === 2">
                  <el-tooltip effect="dark" content="确认收货" placement="top">
                    <el-button style="margin-left: -10px" type="success" icon="el-icon-check" circle @click="takeGoods(item)"></el-button>
                  </el-tooltip>
                </div>
                <div v-if="item.status === 3">
                  <div style="margin-left: 5px">
                    已签收
                  </div>
                </div>
                <div v-if="item.status === 4">
                  <div style="margin-left: 5px">
                    已退款
                  </div>
                </div>
                <div v-if="item.status === 5">
                  <div style="margin-left: 5px">
                    已取消
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-loading="loading" element-loading-text="加载中..." class="no-info" v-else>
          <div style="padding: 100px 0;text-align: center">
            你还未创建过订单
          </div>
        </div>

        <!-- 发布商品评价对话框 -->
        <el-dialog title="写下你的评价吧" :visible.sync="commentVisible" width="760px" @close="commentDialogCLosed">
          <!-- 富文本编辑器 -->
          <quill-editor style="height: 200px" ref="myQuillEditor" v-model="goods_comment" :options="editorOption"></quill-editor>
          <el-card style="margin-top: 60px">
            <el-row :gutter="20" v-if="order_goodsInfo">
              <el-col :span="20" >
                <div class="comment-box">
                  <div class="comment-img">
                    <el-image style="width: 80px" :src="'http://127.0.0.1:8000/' + order_goodsInfo.mp_good.goods_Bigimg" alt=""> </el-image>
                  </div>
                  <div style="margin-left: 15px">
                    <span class="good-title">{{order_goodsInfo.mp_good.goods_name}}</span>
                    <h3>{{ order_goodsInfo.mp_good.goods_describe }}</h3>
                  </div>
                </div>
              </el-col>
              <el-col>
                <div class="comment-box">
                  <span style="margin-top: 10px">与商品描述相符</span>
                  <el-rate style="margin: 10px 0px 0px 10px" v-model="good_rate" :colors="colors" show-text> </el-rate>
                </div>
              </el-col>
            </el-row>
          </el-card>
          
          <div slot="footer" class="dialog-footer">
            <el-button @click="commentVisible = false">取 消</el-button>
            <el-button type="primary" @click="comGood()">确 定</el-button>
          </div>
        </el-dialog>

        <!-- 展示物流进度的对话框 -->
        <el-dialog title="物流进度" :visible.sync="progressVisible" width="50%">
          <!-- 时间线 -->
          <el-timeline :reverse="false">
            <el-timeline-item v-for="(activity, index) in progressInfo" :key="index" :timestamp="activity.time" :color="index === 0 ? '#409EFF' : ''">
              {{ activity.context }}
            </el-timeline-item>
          </el-timeline>
        </el-dialog>

        <!-- 富文本触发的上传 -->
        <el-upload
          class="comment_uploader"
          :action="uploadURL"
          name="file"
          :show-file-list="false"
          :headers="headersObj"
          list-type="picture"
          :on-success="uploadSuccess"
          :on-error="uploadError">
        </el-upload>
      </div>
    </m-shelf>
    <div style="float:right">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next"
        :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import MShelf from '../../../components/shelf.vue'
import { getOrderInfo, pay, remove, getkuaidi, updateOrderStatus, createOrder } from '../../../api/order'
import { createComment } from '../../../api/comment'

const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
  [{ header: 1 }, { header: 2 }], // 1、2 级标题
  [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
  [{ indent: "-1" }, { indent: "+1" }], // 缩进
  [{ size: ["small", false, "large", "huge"] }], // 字体大小
  ["clean"], // 清除文本格式
  ["link", "image"] // 链接、图片、视频
];

export default {
  name: 'Order',
  data() {
    return {
      // 订单的查询参数
      queryInfo: {
        pageNum: 1,
        pageSize: 5,
        status: null,
      },
      // 订单总条数
      total: 0,
      // 订单列表
      orderlist: [],
      // 订单加载效果
      loading: true,
      // 控制物流进度对话框的显示与隐藏
      progressVisible: false,
      progressInfo: [],
      // 上传图片的URL地址
      uploadURL: 'http://127.0.0.1:8000/comments/upload',
      // 图片上传组件的 headers 请求头对象
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 控制评论对话框的显示与隐藏
      commentVisible: false,
      // 被评价的商品的信息
      order_goodsInfo: '',
      // 商品评价
      goods_comment: null,
      // 商品评分
      good_rate: 5,
      // 评分星星的颜色
      colors: ['#99A9BF', '#F7BA2A', '#FF9900'],
      // 富文本编辑器的配置
      editorOption: {
        modules: {
          toolbar: {
            container: toolbarOptions,
            handlers: {
              image: function(value) {
                if (value) {
                    // 触发input框选择图片文件
                    document.querySelector(".comment_uploader input").click();
                  } else {
                    this.quill.format("image", false);
                  }
              }
            }
          }
        },
        placeholder: '请在这里写下您对该商品的评价吧', //提示
      },
      // 订单分类列表
      cateList: [
        {
          value: 0,
          label: '未付款'
        },
        {
          value: 1,
          label: '已付款'
        },
        {
          value: 2,
          label: '已发货'
        },
        {
          value: 3,
          label: '已签收'
        },
        {
          value: 4,
          label: '已退款'
        },
        {
          value: 5,
          label: '已取消'
        }
      ],
    }
  },
  created() {
    this.getOrderList()
  },
  methods: {
    // 获取用户订单信息
    async getOrderList() {
      let { data: res } = await getOrderInfo(this.queryInfo)

      if(res.code !== 0) {
        return this.$notify.error({
          title: '警告',
          message: '获取订单信息失败'
        })
      }

      const list = res.result.list.map(item => {
        item.goods_info = item.mp_order_goods
        delete item.mp_order_goods
        return item
      })

      this.orderlist = list
      this.total = res.result.total
      this.loading = false
      console.log(this.orderlist)
    },
    // 监听一页显示条数变化的函数
    handleSizeChange(newSize) {
      console.log(newSize)
      this.queryInfo.pageSize = newSize
      this.getOrderList()
    },
    // 监听页码变化的函数
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage
      this.getOrderList()
    },
    // 支付函数
    async orderPayment(id, total) {
      // 弹框支付须知
      const confirmResult = await this.$confirm('支付成功后请耐心等待页面跳转！', '提示', {
        confirmButtonText: '我知道了',
        cancelButtonText: '我再想想',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult !== 'confirm') {
        return 
      }
      
      const { data: res } = await pay({id, total})
      window.open(res.result)
    },
    // 查看订单详情
    async goOrderDetail(order_number) {
      this.$router.push('/user/orderDetail/' + order_number)
    },
    // 查看商品详情
    goodsDetails(id) {
      window.open('//' + window.location.host + `/#/goodsDetail/${Number(id)}`)
    },
    // 查看商品物流信息
    async showProgressBox(goodInfo) {
      const { data: res} = await getkuaidi(goodInfo.kuaidi_number)

      if (res.code !== 0) {
        return this.$notify.error({
          title: '警告',
          message: '获取物流进度失败！'
        })
      }
      this.progressInfo = res.result
      this.progressVisible = true
    },
    // 控制评论对话框的显示
    openCommentVisible(order_goodsInfo) {
      this.commentVisible = true
      this.order_goodsInfo = order_goodsInfo
    },
    // 评论对话框关闭触发事件
    commentDialogCLosed() {
      this.goods_comment = null
      this.good_rate = 5
    },
    // 富文本图片上传成功后的事件
    async uploadSuccess(res) {
      let quill = this.$refs.myQuillEditor.quill;

      if(res.code !== 0) {
        return this.$notify.error({
          title: '警告',
          message: '图片插入失败'
        })
      }
      let length = quill.getSelection().index;
      quill.insertEmbed(length, "image", `http://127.0.0.1:8000/${res.result.comment_img}`);
      quill.setSelection(length + 1);
    },
    // 富文本图片上传失败
    uploadError() {
      return this.$notify.error({
        title: '警告',
        message: '图片插入失败'
      })
    },
    // 评论商品
    async comGood(){
      if(this.goods_comment === null || this.goods_comment === '' || this.good_rate === null || this.good_rate === ''){
        return this.$notify.info({
          title: '消息',
          message: '给商品留下您的评价吧'
        })
      }
      // 弹框确认用户是否确认发布评论
      const confirmResult = await this.$confirm('评价只能填写一次噢，确认发布？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).catch(err => err)

      // 如果用户确认发布，则返回字符串 confirm,取消则是 cancel
      if (confirmResult !== 'confirm') {
        return 
      }

      const { data: res } = await createComment({
        goods_id: this.order_goodsInfo.goods_id,
        order_id: this.order_goodsInfo.order_id,
        order_goods_id: this.order_goodsInfo.id,
        score: this.good_rate,
        content: this.goods_comment
      })
      console.log(res)
      if(res.code !== 0) {
        return this.$notify.error({
          title: '警告',
          message: '发表评价失败'
        })
      }
      /* console.log(this.order_goodsInfo)
      console.log(this.goods_comment) */
      this.commentVisible = false
      this.getOrderList()
    },

    // 确认收货
    async takeGoods(orderInfo) {
      const id = orderInfo.id
      const { data: res } = await updateOrderStatus(id, { status: 3 })

      if (res.code !== 0) {
        return this.$notify.error({
          title: '警告',
          message: '更新订单状态失败！'
        })
      }
      
      this.getOrderList()
    },
    // 删除订单
    async delOrder(id, order_number){
      // 弹框确认用户是否删除数据
      const confirmResult = await this.$confirm(`是否删除订单${order_number}`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).catch(err => err)

      // 如果用户确认删除，则返回字符串 confirm,取消则是 cancel
      if (confirmResult !== 'confirm') {
        return 
      }

      const { data: res } = await remove(id)

      if(res.code !== 0) {
        return this.$notify.error({
          title: '警告',
          message: '删除订单失败'
        })
      }

      this.getOrderList()
    },
    // 级联选择器选中项变化，会触发这个函数
    handleChange() {
      if (this.queryInfo.status === '') {
        this.queryInfo.status = null
      }
      this.queryInfo.pageNum = 1
      this.getOrderList()
    },

    // 处理时间格式的函数
    dateFormat(originVal) {
      const dt = new Date(originVal)

      // 时间戳
      /* const time = dt.getTime()
      console.log(time)  */

      const y = dt.getFullYear()
      const m = (dt.getMonth() + 1 + '').padStart(2, '0')
      const d = (dt.getDate() + '').padStart(2, '0')

      const hh = (dt.getHours() + '').padStart(2, '0')
      const mm = (dt.getMinutes() + '').padStart(2, '0')
      const ss = (dt.getSeconds() + '').padStart(2, '0')

      return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
    }
  },
  components: {
    MShelf
  }
}
</script>

<style lang="scss" scoped>
@import "../../../assets/style/mixin";
.gray-sub-title {
  height: 38px;
  padding: 0 24px;
  background: #EEE;
  border-top: 1px solid #DBDBDB;
  border-bottom: 1px solid #DBDBDB;
  line-height: 38px;
  font-size: 12px;
  color: #666;
  display: flex;
  span {
    display: inline-block;
    height: 100%;
  }
  .first {
    display: flex;
    justify-content: space-between;
    flex: 1;
    .f-bc {
      > span {
        width: 112px;
        text-align: center;
      }
    }
  }
  .last {
    width: 230px;
    text-align: center;
    display: flex;
    border-left: 1px solid #ccc;
    span {
      flex: 1;
    }
  }
}

.bt {
  border-top: 1px solid #EFEFEF;
}

.date {
  padding-left: 0px;
}

.order-id {
  margin-left: 25px;
}

.cart {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 24px;
  &:hover {
    .del-order {
      display: block;
    }
  }
  .del-order {
    display: none;
  }
  .cart-l {
    display: flex;
    align-items: center;
    flex: 1;
    padding: 15px 0;
    justify-content: space-between;
    position: relative;
    &:before {
      position: absolute;
      content: ' ';
      right: -1px;
      top: 0;
      width: 1px;
      background-color: #EFEFEF;
      height: 100%;
    }
    .ellipsis {
      margin-left: 20px;
      width: 220px;
    }
    .img-box {
      border: 1px solid #EBEBEB;
    }
    img {
      display: block;
      @include wh(80px);
    }
    .cart-l-r {
      display: flex;
      > div {
        text-align: center;
        line-height: 42px;
        width: 112px;
      }
    }
    .car-l-l {
      display: flex;
      align-items: center;
    }
  }
  .cart-r {
    width: 230px;
    display: flex;
    span {
      text-align: center;
      flex: 1;
    }
  }
}

.prod-operation {
  height: 110px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 254px;
  div {
    width: 100%;
    text-align: center;
  }
  div:last-child {
    padding-right: 24px;
  }
}

.comment-box {
  display: flex;
  justify-items: center;
  align-items: center;
  .good-title {
    line-height: 1.2;
    font-size: 16px;
    color: #424242;
    margin: 0 auto;
    padding: 0 14px;
    text-align: center;
    overflow: hidden;
  }
  h3 {
    text-align: center;
    line-height: 1.2;
    font-size: 12px;
    color: #d0d0d0;
    padding: 10px;
  }
}

.el-select {
  width: 120px;
}
</style>